<template>
    <el-card>
        <!-- 标题部分 -->
        <div class="box">
            <div class="short"></div>

            <div>{{ route.query._id ? '编辑医生信息' : '新增医生信息' }}</div>
        </div>

        <!-- 表单部分 -->
        <el-form ref="doctorFormRef" :model="doctorInfo" :rules="rules" label-width="100px" style="margin-top: 20px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="医生编号">
                        <el-input v-model="doctorInfo._id" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="账号" prop="phone">
                        <el-input v-model="doctorInfo.phone" placeholder="请输入有效手机号码" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="医生头像">
                        <el-upload class="avatar-uploader" :action="`${baseURL}/images/upload`" :show-file-list="false"
                            :on-success="handleAvatarSuccess">
                            <img v-if="doctorInfo.avatar" :src="doctorInfo.avatar" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="医生姓名" prop="name">
                        <el-input v-model="doctorInfo.name" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="医生角色" prop="roleId">
                        <el-select v-model="doctorInfo.roleId" placeholder="请选择">
                            <el-option v-for="item in DoctorRolesData.rows" :key="item._id" :label="item.name"
                                :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="登录密码" prop="password">
                        <el-input v-model="doctorInfo.password" placeholder="请输入" type="password" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="doctorInfo.gender" placeholder="请选择">
                            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="所属机构">
                        <el-select v-model="doctorInfo.organizationId" placeholder="请选择" clearable>
                            <el-option v-for="item in AgencyData.rows" :key="item._id" :label="item.name"
                                :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="18">
                    <el-form-item label="医生简介">
                        <el-input v-model="doctorInfo.intro" type="textarea" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="18">
                    <el-form-item label="医生擅长">
                        <el-input v-model="doctorInfo.skill" type="textarea" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" @click="handleSave">保存</el-button>
                        <el-button @click="$router.back">返回</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useFindData } from '../../../composables/findData'
import { addDoctorApi, getDoctorInfoApi, updataDoctorApi } from '../../../api/doctorManage';
import { useRoute } from 'vue-router';
import { Plus } from '@element-plus/icons-vue'

const baseURL = import.meta.env.VITE_BASE_URL


// 路由实例，用于获取编辑的id
const route = useRoute()
// 判断是否为编辑状态（有id则为编辑）
const isEdit = ref(!!route.query._id)
// 表单引用
const doctorFormRef = ref(null)

// 表单数据
const doctorInfo = ref({
    _id: '',
    phone: '',
    avatar: '',
    name: '',
    roleId: '',
    password: '',
    gender: '',
    intro: '医术高超',
    skill: '外科',
    organizationId: ''
})

// 下拉选项数据
const { DoctorRolesData, findDoctorRolesAsync, AgencyData, findAgencyAsync } = useFindData()

const genderOptions = reactive([
    { label: '男', value: 1 },
    { label: '女', value: 0 }
])


// 表单验证规则
const rules = reactive({
    phone: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入医生姓名', trigger: 'blur' },
        { min: 2, message: '姓名至少包含两个字符', trigger: 'blur' }
    ],
    roleIdName: [
        { required: true, message: '请选择医生角色', trigger: 'change' }
    ],
    password: [
        { required: true, message: '请输入登录密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ]
})

// 获取医生详情（编辑时用）
const getDoctorDetail = async (id) => {
    try {
        const res = await getDoctorInfoApi({ _id: id })
        if (res.code === 200) {
            const doctor = res.data
            //拿到当前选中的机构名称
            const organizationId = doctor.organizationId?._id || doctor.organizationId;

            doctorInfo.value = {
                _id: doctor._id,
                phone: doctor.phone,
                avatar:doctor.avatar,
                name: doctor.name,
                roleIdName: doctor.roleId?.name,
                roleId: doctor.roleId?._id,
                password: doctor.password,
                gender: doctor.gender,
                intro: doctor.intro || '医术高超',
                skill: doctor.skill || '外科',
                organizationId: organizationId
            }
        }
    } catch (err) {
        console.error('获取医生详情失败：', err)
        ElMessage.error('加载编辑数据失败')
    }
}

// 上传头像成功回调
const handleAvatarSuccess = (res) => {
    if(res.code == 200){
        doctorInfo.value.avatar = res.data
    }
}

// 保存按钮逻辑
const handleSave = () => {
    doctorFormRef.value.validate((valid) => {
        if (valid) {
            console.log("---------------------" + route.query._id);
            console.log("--------" + isEdit);

            if (route.query._id) {
                console.log(doctorInfo.value);
                updataDoctorApi({
                    ...doctorInfo.value,

                }).then(res => {
                    if (res.code == 200) {
                        ElMessage.success('修改成功！')
                    }
                })
            } else {
                console.log("-----------新增--");
                addDoctorApi({
                    ...doctorInfo.value,
                }).then(res => {
                    if (res.code == 200) {
                        ElMessage.success('新增成功！')
                        doctorInfo.value = {
                            _id: '',
                            phone: '',
                            avatar: '',
                            name: '',
                            roleId: '',
                            password: '',
                            gender: '',
                            intro: '医术高超',
                            skill: '外科'
                        }
                    }
                }).catch(res => {
                    ElMessage.warning(res.message)
                })
            }
        } else {
            ElMessage.error('表单验证失败，请检查必填项')
            return false
        }
    })
}


onMounted(() => {
    findDoctorRolesAsync();
    findAgencyAsync();

    // 如果是编辑，根据id请求详情并回显
    if (isEdit.value) {
        getDoctorDetail(route.query._id)
    }
})

</script>

<style scoped lang="scss">
.avatar-uploader {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    border: 1px dashed var(--el-border-color);
    text-align: center;
    cursor: pointer;

    .avatar {
        width: 100%;
        height: 100%;
        border-radius: 8px;
    }

    .el-icon.avatar-uploader-icon {
        font-size: 20px;
        color: #5f90d4;
        width: 60px;
        height: 60px;
        text-align: center;
    }

}
</style>